package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.CommentAdapter;
import com.xgkj.diyiketang.activity.data.TieZiAdapter;
import com.xgkj.diyiketang.data.CommentInfo;
import com.xgkj.diyiketang.data.PengYouQuanInfo;
import com.xgkj.diyiketang.data.PhotoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.CommentListTask;
import com.xgkj.diyiketang.task.PublishCommentTask;
import com.xgkj.diyiketang.task.ZanDiaryTask;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MyCustomListView;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.weidget.NoScrollGridView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/7/28.
 */
public class PengYouQuanDetailActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    //    private NoScrollGridView mGridView;
//    private TieZiAdapter mAdapter;
    private TextView back;
    private LinearLayout picList1;
    private LinearLayout picList2;
    private Button pinglunBtn;
    private String cmtText;
    private ClearableEditText cmtContant;
    private int commentListTaskId = -1;
    private int publishCmtTaskId = -1;
    private int currentPage = 1;
    private MyCustomListView commentList;
    private CommentAdapter cmtAdapter;
    private String vdid;
    private MyScrollView mySroll;
    private ImageView mZanBtn;
    private int zanTaskId = -1;
    private String haveup;
    private PengYouQuanInfo info;
    private ImageView mUserLogo;
    private TextView mUserNick;
    private TextView mContent;
    private TextView mTime;
//    private List<PhotoInfo> bmList = new ArrayList<PhotoInfo>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pengyouquandetail);
        mContext = this;
        initView();
    }

    private void initView() {
        final Intent intent = getIntent();
        info = (PengYouQuanInfo) intent.getSerializableExtra("INFO");
        vdid = info.getDairyId();
        PalLog.e("日记的ID",vdid);
        haveup = info.getHaveUp();


        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mySroll = (MyScrollView) findViewById(R.id.detail_scroll);
        mySroll.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll() {
                getCommentList();
            }
        });

        picList1 = (LinearLayout) findViewById(R.id.pic_list);
        picList2 = (LinearLayout) findViewById(R.id.pic_list2);
        mUserLogo = (ImageView) findViewById(R.id.head_icon);
        mUserNick = (TextView) findViewById(R.id.nickname);
        mContent = (TextView) findViewById(R.id.content_desc);
        mTime = (TextView) findViewById(R.id.time);
        mZanBtn = (ImageView) findViewById(R.id.zan);
        mZanBtn.setOnClickListener(this);

        if (info != null) {

            String anchorImgUrl = info.getUserLogo();
            if (anchorImgUrl != null && anchorImgUrl.length() > 0) {
                ViewUtil.Size size = ViewUtil.getHeadImageSize_40(mContext);
                Bitmap cacheBitmap = ImageCache.getInstance(mContext).getBitmapFromMemoryCache(ImageCache.getInstance(mContext).getCacheKey(anchorImgUrl, size));
                if (cacheBitmap != null) {
                    mUserLogo.setImageBitmap(cacheBitmap);
                } else {
                    mUserLogo.setImageResource(R.drawable.default_head_image);
                    ImageCache.getInstance(mContext).loadBitmapToView(mUserLogo, anchorImgUrl, size);
                }
            }
            if (info.getNickName() != null) {
                try {
                    mUserNick.setText(URLDecoder.decode(info.getNickName(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (info.getDairyContent() != null) {
                try {
                    mContent.setText(URLDecoder.decode(info.getDairyContent(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            mTime.setText(info.getDairyTime());

            if (haveup.equals("1")) {
                mZanBtn.setClickable(false);
                mZanBtn.setImageResource(R.drawable.zan_checked);
            }

            String ss = info.getDairyImage();
            List<String> apdlist = Arrays.asList(ss.split(";"));

//            PalLog.e("拆分的图片list数量",apdlist.size()+"");
            final ArrayList<String> adlist = new ArrayList<String>();
            for (int i =0;i<apdlist.size();i++){
                adlist.add(apdlist.get(i));
            }


            picList1.removeAllViews();
            if (adlist != null && adlist.size() > 0 ) {

                for (int i = 0; i < adlist.size(); i++) {
                    ImageView image = new ImageView(mContext);
                    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
                    params.setMargins(0,10,20,10);
                    image.setLayoutParams(params);
                    ViewUtil.Size size = new ViewUtil.Size(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
                    String url = adlist.get(i);
                    if (url != null && url.length() > 0) {
                        ImageCache.getInstance(mContext).loadBitmapToView(image, url, size);
                    }
                    final int finalI = i;
                    image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent pic1intent = new Intent(mContext,ShowBigImageActivity.class);
                            pic1intent.putExtra("photoList",adlist);
                            pic1intent.putExtra("currentPosition", finalI);
                            startActivity(pic1intent);
                        }
                    });
                    picList1.addView(image);
                    if(i == 2){
                        break;
                    }
                }
            }
            picList1.requestLayout();

            picList2.removeAllViews();
            if(adlist!=null && adlist.size()>3 ){

                for (int i = 3; i < adlist.size(); i++) {
                    ImageView image = new ImageView(mContext);
                    image.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
                    params.setMargins(0,10,20,10);
                    image.setLayoutParams(params);
                    ViewUtil.Size size = new ViewUtil.Size(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
                    String url = adlist.get(i);
                    if (url != null && url.length() > 0) {
                        ImageCache.getInstance(mContext).loadBitmapToView(image, url, size);
                    }
                    final int finalI = i;
                    image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent pic1intent = new Intent(mContext,ShowBigImageActivity.class);
                            pic1intent.putExtra("photoList",adlist);
                            pic1intent.putExtra("currentPosition", finalI);
                            startActivity(pic1intent);
                        }
                    });
                    picList2.addView(image);
                    if (i==5){
                        break;
                    }
                }
            }
            picList2.requestLayout();

        }

        pinglunBtn = (Button) findViewById(R.id.fabiaopinglun);
        pinglunBtn.setOnClickListener(this);


        cmtContant = (ClearableEditText) findViewById(R.id.pinglun);
        commentList = (MyCustomListView) findViewById(R.id.comment_list);
        cmtAdapter = new CommentAdapter(mContext, vdid, 1);

        commentList.setAdapter(cmtAdapter);

//        ArrayList<String> adlist = new ArrayList<String>();
//        adlist.add("http://v1.qzone.cc/skin/201310/08/17/18/5253cde1709ed704.jpg!600x600.jpg");
//        adlist.add("http://v1.qzone.cc/skin/201310/08/17/18/5253cdfb94297789.jpg!600x600.jpg");
//        adlist.add("http://v1.qzone.cc/skin/201310/08/17/18/5253ce037d97f728.jpg!600x600.jpg");
//        adlist.add("http://v1.qzone.cc/skin/201310/08/17/16/5253cd697a68b403.jpg!600x600.jpg");
//        adlist.add("http://v1.qzone.cc/skin/201310/08/17/19/5253ce06a29c2425.jpg!600x600.jpg");
//        adlist.add("http://pic49.nipic.com/file/20140928/4949133_154705706000_2.jpg");
//        picList1.removeAllViews();
//        if (adlist != null && adlist.size() > 0) {
//
//            for (int i = 0; i < 3; i++) {
//                ImageView image = new ImageView(mContext);
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//                params.setMargins(0, 10, 20, 10);
//                image.setLayoutParams(params);
//                ViewUtil.Size size = new ViewUtil.Size(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
//                String url = adlist.get(i);
//                if (url != null && url.length() > 0) {
//                    ImageCache.getInstance(mContext).loadBitmapToView(image, url, size);
//                }
//
//                picList1.addView(image);
//            }
//        }
//        picList2.removeAllViews();
//        if (adlist != null && adlist.size() > 0) {
//
//            for (int i = 3; i < 6; i++) {
//                ImageView image = new ImageView(mContext);
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//                params.setMargins(0, 10, 20, 10);
//                image.setLayoutParams(params);
//                ViewUtil.Size size = new ViewUtil.Size(ViewUtil.dip2px(mContext, 80), ViewUtil.dip2px(mContext, 80));
//                String url = adlist.get(i);
//                if (url != null && url.length() > 0) {
//                    ImageCache.getInstance(mContext).loadBitmapToView(image, url, size);
//                }
//
//                picList2.addView(image);
//            }
//        }
//        mGridView = (NoScrollGridView) findViewById(R.id.tiezi_list);
//        mAdapter = new TieZiAdapter(mContext);
//        mGridView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fabiaopinglun:
                if (checkInput()) {
                    publishComment();
                    cmtContant.setText(null);
                }

                break;
            case R.id.zan:
                doZan();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentPage = 1;
        getCommentList();
    }

    private void doZan() {
        ZanDiaryTask dtask = new ZanDiaryTask(vdid);
        dtask.addListener(new VideoDetailTaskListener(mContext));
        zanTaskId = getEatShowApp().getTaskManager().addTask(dtask);
    }

    private void publishComment() {
        //cmtText = cmtContant.getText().toString().trim();
        PublishCommentTask pcTask = new PublishCommentTask(vdid, cmtText, "", "");
        pcTask.addListener(new VideoDetailTaskListener(mContext));
        publishCmtTaskId = getEatShowApp().getTaskManager().addTask(pcTask);
    }

    private void getCommentList() {
        if (currentPage == 0) {
            commentList.setNoNextPage();
            return;
        }
        CommentListTask cmtListTask = new CommentListTask(10, currentPage, vdid);
        cmtListTask.addListener(new VideoDetailTaskListener(mContext));
        commentListTaskId = getEatShowApp().getTaskManager().addTask(cmtListTask);

    }

    class VideoDetailTaskListener extends ShowToastTaskEventListener {

        public VideoDetailTaskListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == publishCmtTaskId) {
                Toast.makeText(mContext, R.string.pinglun_success, Toast.LENGTH_SHORT)
                        .show();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(cmtContant.getWindowToken(), 0);
                cmtContant.setText("");

                currentPage = 1;
                getCommentList();
            } else if (taskId == commentListTaskId) {
                if (data != null) {
                    List<CommentInfo> list = (List<CommentInfo>) data;
                    if (currentPage == 1) {
                        cmtAdapter.clearData();
                    }
                    if (list != null && list.size() > 0) {
                        cmtAdapter.updateData(list);
                    }
                    currentPage = result;
                }
            } else if (taskId == zanTaskId) {

                mZanBtn.setClickable(false);
                mZanBtn.setImageResource(R.drawable.zan_checked);
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private boolean checkInput() {
        cmtText = cmtContant.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }
}
